<template>
  <div>
    <div class="flex justify-end w-full mb-4">
      <div class="relative">
        <el-button class="w-32" type="primary">添加原料</el-button>
      </div>
    </div>
    <el-table :data="meterialList" border>
      <el-table-column prop="name" label="原料名称" min-width="100"></el-table-column>
      <el-table-column prop="code" label="编码"></el-table-column>
      <el-table-column prop="unit" label="单位"></el-table-column>
      <el-table-column prop="price" label="单价" min-width="180">
        <template #default="{ row }">
          <el-input-number v-model="row.price" :min="0" :precision="2" :controls="false"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ $index }">
          <el-button type="danger" link size="small" @click="onRemoveMeterial($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4">
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="onClose">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { supplierPriceServer } from '@/api'
import { ref } from 'vue'
import { divi, mult } from '@/utils'
import { ElMessage } from 'element-plus'
const props = defineProps({
  info: Object,
});
const emit = defineEmits(['close', 'success'])

const getMeterialList = async () => {
  if (!props.info.id) {
    return
  }
  const { data } = await supplierPriceServer.get({
    supply_id: props.info.id,
  })
  const list = data || []
  list.forEach(v => {
    v.price = divi(v.price)
  });
  meterialList.value = list
}
getMeterialList()

const meterial = ref(null)
const meterialList = ref([])

const onAddMeterial = (val) => {
  meterial.value = null;
  if (meterialList.value.some(item => item.id === val.id)) {
    ElMessage.error('该原料已添加');
    return;
  }
  meterialList.value.push({
    material_id: val.id,
    code: val.code,
    name: val.name,
    unit: val.unit,
    price: 0,
  })
}
const onRemoveMeterial = (index) => {
  meterialList.value.splice(index, 1)
}

const onSubmit = async () => {
  const price_list = meterialList.value.map(item => ({
    material_id: item.material_id,
    price: mult(item.price),
  }))

  if (price_list.some(v => v.price === 0)) {
    ElMessage.error('价格不能为0');
    return;
  }

  await supplierPriceServer.put({
    supply_id: props.info.id,
    price_list,
  })
  ElMessage.success('保存成功');
  emit('success')
  onClose()
}
const onClose = () => {
  emit('close')
}
</script>

<style lang="scss" scoped>
.fixed-select :deep(.el-select__wrapper) {
  opacity: 0;

  &.is-focused {
    opacity: 1;
  }
}
</style>